import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:travel/components/hotel/order.dart';
import 'package:travel/model/hotel.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/context.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:travel/screen/flutter_screenutil.dart';

class HotelOrderListController extends GetxController with GetTickerProviderStateMixin {
  /// 订单类型
  RxList<OrderTypeEnum> tabs = RxList([]);

  RxInt tabIndex = 0.obs;

  RxBool isOpen = false.obs;

  late GlobalKey topKey;

  OverlayEntry? _overlayEntry;

  late TabController tabController;

  RxInt index = 0.obs;

  RxList<String> tabList = RxList(['全部', '待付款', '未使用', '已取消', '已使用']);

  @override
  void onInit() {
    topKey = GlobalKey();
    tabController = TabController(length: tabList.length, vsync: this);
    tabs.value = OrderTypeEnum.values;
    super.onInit();
  }

  /// 显示浮层
  void showOverlay(BuildContext context) {
    if (isOpen.isTrue) {
      isOpen.value = false;
      hideOverlay();
      return;
    }
    isOpen.value = true;

    /// 防止重复创建，不然失去句柄的OverlayEntry将无法消除
    if (_overlayEntry == null) {
      _overlayEntry = createOverlayEntry();
      if (_overlayEntry != null) {
        Overlay.of(context).insert(_overlayEntry!);
      }
    }
  }

  /// 创建浮层
  OverlayEntry createOverlayEntry() {
    Size? o = topKey.size;
    o ??= Size.zero;
    return OverlayEntry(
      builder: (BuildContext context) {
        return GestureDetector(
          onTap: hideOverlay,
          child: Transform.translate(

              /// 40.h高度表示tabList 选择
              offset: Offset(0, o!.height + 5 - 40.h),
              child: Material(
                color: Colors.transparent,
                child: Align(
                  alignment: Alignment.topLeft,
                  child: Container(
                    width: Get.width,
                    height: 100.h,
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    alignment: Alignment.center,
                    color: Colors.white,
                    child: StaggeredGrid.count(
                      crossAxisCount: 2,
                      mainAxisSpacing: 10.w,
                      crossAxisSpacing: 10.h,
                      children: tabs
                          .asMap()
                          .map((index, row) => MapEntry(
                              index,
                              InkWell(
                                onTap: () {
                                  isOpen.value = false;
                                  tabIndex.value = index;
                                  hideOverlay();
                                },
                                child: Container(
                                  constraints: BoxConstraints.expand(width: 160.w, height: 40.h),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(5.w),
                                      color: activeColor(index),
                                      border: Border.all(color: borderColor(index))),
                                  child: Text(
                                    '${row.label}订单',
                                    style: StylesUtils.customTextStyle(
                                        color: tabIndex.value == index
                                            ? ColorsUtils.color3478
                                            : ColorsUtils.color5555),
                                  ),
                                ),
                              )))
                          .values
                          .toList(),
                    ),
                  ),
                ),
              )),
        );
      },
    );
  }

  /// 隐藏浮层
  void hideOverlay() {
    isOpen.value = false;

    /// 防止null调用异常
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }

  Color activeColor(int index) {
    if (tabIndex.value == index) {
      return ColorsUtils.rgba(52, 120, 246, 0.0470588);
    }
    return Colors.white;
  }

  Color borderColor(int index) {
    if (tabIndex.value == index) {
      return ColorsUtils.rgba(52, 120, 246, 0.447059);
    }
    return ColorsUtils.rgba(228, 228, 228);
  }

  @override
  void onClose() {
    tabController.dispose();
    hideOverlay();
    super.onClose();
  }
}

class HotelOrderListView extends GetView<HotelOrderListController> {
  const HotelOrderListView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
          appBar: AppBar(
            key: controller.topKey,
            automaticallyImplyLeading: true,
            backgroundColor: Colors.white,
            leading: InkWell(
              onTap: Get.back,
              child: Icon(
                Icons.arrow_back_ios,
                color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                size: 20.w,
              ),
            ),
            leadingWidth: 40.w,
            title: Center(
              child: InkWell(
                onTap: () {
                  controller.showOverlay(context);
                },
                child: Text.rich(TextSpan(children: [
                  TextSpan(
                    text: '${controller.tabs[controller.tabIndex.value].label}订单',
                    style:
                        StylesUtils.customTextStyle(fontSize: 16.sp, color: ColorsUtils.color0000),
                  ),
                  WidgetSpan(
                      child: Icon(
                        controller.isOpen.isTrue ? Icons.arrow_drop_down : Icons.arrow_drop_up,
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                        size: 20.sp,
                      ),
                      alignment: PlaceholderAlignment.middle)
                ])),
              ),
            ),
            actions: [
              IconButton(
                icon: Icon(
                  Icons.search_sharp,
                  color: ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                  size: 25.sp,
                ),
                onPressed: () {
                  Get.toNamed(RoutePath.hotelOrderSearch);
                },
              ),
            ],
            bottom: PreferredSize(
                preferredSize: Size.fromHeight(40.h),
                child: Container(
                  color: Colors.white,
                  alignment: Alignment.centerLeft,
                  child: ToolsUtils.getClientTabBar(controller.tabList, controller.tabController,
                      isScrollable: false),
                )),
          ),
          body: TabBarView(
            controller: controller.tabController,
            children: [
              OrderAll(orderType: controller.tabs[controller.tabIndex.value]),
              OrderUnpaid(orderType: controller.tabs[controller.tabIndex.value]),
              OrderUnused(orderType: controller.tabs[controller.tabIndex.value]),
              OrderCancelled(orderType: controller.tabs[controller.tabIndex.value]),
              OrderUsed(orderType: controller.tabs[controller.tabIndex.value])
            ],
          ),
        ));
  }

  Color activeColor(int index) {
    if (controller.tabIndex.value == index) {
      return ColorsUtils.rgba(52, 120, 246, 0.0470588);
    }
    return Colors.white;
  }

  Color borderColor(int index) {
    if (controller.tabIndex.value == index) {
      return ColorsUtils.rgba(52, 120, 246, 0.0470588);
    }
    return ColorsUtils.rgba(228, 228, 228);
  }
}
